Imports System.Data.Common
Imports System.Net.Mail
Partial Class Presentation_ContactEntry
    Inherits System.Web.UI.Page

    Protected Sub Validate_TelEmail(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvdtxtTelephone.ServerValidate

        If txtEmail.Text = "" And txtTelephone.Text = "" And txtMobile.Text = "" Then
            args.IsValid = False
        Else

            args.IsValid = True

        End If

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim Sql As String
        Dim Params(0) As GenParameter
        Dim UID As Integer
        Dim Records As DbDataReader
        Dim SqlForClient As String
        Dim RecordForClient As DbDatareader


        UID = Request.Cookies("Profile").Item("ExecutiveID")

        Page.Title = "Enter a new Contact"

        If Not Page.IsPostBack Then

            'This is common for both modifications and insertions

            dlClientNames.DataValueField = "ClientID"
            dlClientNames.DataTextField = "ClientName"

            'Check and see if the page is an Entry or a modification page

            If PreviousPage IsNot Nothing Then

                'Modification

                If PreviousPage.IsCrossPagePostBack Then

                    'Get the Contact details

                    PostBack.Value = PreviousPage.GetUniqueID
                    Sql = "Select ContactName, ContactEmail, Telephone, Mobile, ClientID, Designation FROM ContactMaster" & _
                        " WHERE ContactID = " & PostBack.Value

                    Records = GenHelper.ExecuteReader(Sql, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())


                    'Fill the fields with the data to be updated

                    If Records.Read Then

                        'Populate the Client Drop down list with just the one

                        SqlForClient = "Select ClientID, ClientName FROM ClientMaster" & _
                        " WHERE ClientID = " & Records.Item("ClientID").ToString

                        RecordForClient = GenHelper.ExecuteReader(SqlForClient, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())


                        dlClientNames.DataSource = RecordForClient
                        dlClientNames.DataBind()
                        RecordForClient.Close()


                        txtContactName.Text = Records.Item("ContactName").ToString
                        txtDesignation.Text = Records.Item("Designation").ToString
                        txtEmail.Text = Records.Item("ContactEmail").ToString
                        txtTelephone.Text = Records.Item("Telephone").ToString
                        txtMobile.Text = Records.Item("Mobile").ToString
                        dlClientNames.SelectedValue = Records.Item("ClientID").ToString
                        cbDecision.Enabled = False

                    End If


                End If

            Else
                PostBack.Value = False

                'Populate the Clients Drop down box

                'Call the first function that will empty the box and create the default values
                PopulateClientFirst()

            End If


        End If

    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        If PostBack.Value = False Then

            InsertContact()
        Else
            UpdateContact(PostBack.Value)

        End If


    End Sub

    Protected Sub InsertContact()

        Dim Sql As String
        Dim Params(1) As GenParameter
        Dim Count As Integer

        If Not Page.IsValid Then
            lblSuccess.Visible = False
            Return
        End If

        'Check and see if the Contact is a duplicate

        Sql = "Select Count(*) from ContactMaster where ContactName = ?ContactName AND ClientID = ?ClientID"
        Params(0) = New GenParameter("?ContactName", txtContactName.Text.Trim, Data.DbType.String)
        Params(1) = New GenParameter("?ClientID", dlClientNames.SelectedValue, Data.DbType.UInt16)

        Count = GenHelper.ExecuteScalar(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

        If Count <> 0 Then
            lblSuccess.Text = "This Contact already exists"
            lblSuccess.Visible = True
            Return
        End If



        If cbDecision.Checked = True Then
            ReDim Params(0)

            'Check if there is another decision Maker
            Sql = "Select Count(*) from ContactMaster WHERE ClientID = ?ClientID AND DecisionMaker = 1"
            Params(0) = New GenParameter("?ClientID", dlClientNames.SelectedValue, Data.DbType.UInt32)

            Count = GenHelper.ExecuteScalar(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

            If (Count <> 0) Then

                'Clear all the other decision Makers
                Sql = "UPDATE ContactMaster SET DecisionMaker = 0 WHERE ClientID = ?ClientID"
                GenHelper.ExecuteNonQuery(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

            End If


        End If

        ReDim Params(6)


        Sql = "INSERT INTO ContactMaster (ContactName, ContactEmail, Telephone, Mobile, ClientID, Designation, DecisionMaker)" & _
        " VALUES (?ContactName, ?ContactEmail, ?Telephone, ?Mobile, ?ClientID, ?Designation, ?DecisionMaker)"

        Params(0) = New GenParameter("?ContactName", StrConv(txtContactName.Text.Trim, VbStrConv.ProperCase), Data.DbType.String)
        Params(1) = New GenParameter("?ContactEmail", txtEmail.Text, Data.DbType.String)
        Params(2) = New GenParameter("?Telephone", txtTelephone.Text, Data.DbType.String)
        Params(3) = New GenParameter("?Mobile", txtMobile.Text, Data.DbType.String)
        Params(4) = New GenParameter("?ClientID", dlClientNames.SelectedValue, Data.DbType.UInt32)
        Params(5) = New GenParameter("?Designation", StrConv(txtDesignation.Text.Trim, VbStrConv.ProperCase), Data.DbType.String)
        Params(6) = New GenParameter("?DecisionMaker", cbDecision.Checked, Data.DbType.Boolean)

        GenHelper.ExecuteNonQuery(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())



        'Code to clear the fields

        txtContactName.Text = ""
        txtEmail.Text = ""
        txtTelephone.Text = ""
        txtMobile.Text = ""
        dlClientNames.SelectedIndex = 0
        txtDesignation.Text = ""
        cbDecision.Checked = False
        lblSuccess.Text = "Successfully Entered"
        lblSuccess.Visible = True


    End Sub

    Protected Sub UpdateContact(ByVal ChangeID As Integer)

        Dim Sql As String
        Dim Params(1) As GenParameter
        Dim Count As Integer

        If Not Page.IsValid Then
            lblSuccess.Visible = False
            Return
        End If

        'Check and see if the Contact is a duplicate

        Sql = "Select Count(*) from ContactMaster WHERE ContactName = ?ContactName AND ClientID = ?ClientID" & _
            " AND ContactID <> " & ChangeID
        Params(0) = New GenParameter("?ContactName", txtContactName.Text.Trim, Data.DbType.String)
        Params(1) = New GenParameter("?ClientID", dlClientNames.SelectedValue, Data.DbType.UInt16)

        Count = GenHelper.ExecuteScalar(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

        If Count <> 0 Then
            lblSuccess.Text = "This Contact already exists"
            lblSuccess.Visible = True
            Return
        End If



        ReDim Params(5)


        Sql = "UPDATE ContactMaster" & _
        " SET ContactName = ?ContactName, ContactEmail = ?ContactEmail, Telephone = ?Telephone, Mobile = ?Mobile, ClientID = ?ClientID, Designation = ?Designation" & _
        " WHERE ContactID = " & ChangeID

        Params(0) = New GenParameter("?ContactName", StrConv(txtContactName.Text.Trim, VbStrConv.ProperCase), Data.DbType.String)
        Params(1) = New GenParameter("?ContactEmail", txtEmail.Text, Data.DbType.String)
        Params(2) = New GenParameter("?Telephone", txtTelephone.Text, Data.DbType.String)
        Params(3) = New GenParameter("?Mobile", txtMobile.Text, Data.DbType.String)
        Params(4) = New GenParameter("?ClientID", dlClientNames.SelectedValue, Data.DbType.UInt32)
        Params(5) = New GenParameter("?Designation", StrConv(txtDesignation.Text.Trim, VbStrConv.ProperCase), Data.DbType.String)

        GenHelper.ExecuteNonQuery(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

        ' Send an Email
        Dim Message As String


        Dim Mail As New MailMessage()

        Mail.From = New MailAddress(User.Identity.Name)
        Mail.To.Add("bhagwad@zakgroup.com")
        Message = txtContactName.Text & " " & txtEmail.Text & " " & txtTelephone.Text & " " & txtMobile.Text & " " & dlClientNames.SelectedValue & " " & txtDesignation.Text
        Mail.Subject = "Contact's Details Changed"

        Mail.Body = Message

        Dim smtp As New SmtpClient("127.0.0.1")
        smtp.Send(Mail)

        'Code to clear the fields

        txtContactName.Text = ""
        txtEmail.Text = ""
        txtTelephone.Text = ""
        txtMobile.Text = ""
        dlClientNames.SelectedIndex = 0
        txtDesignation.Text = ""
        cbDecision.Checked = False
        cbDecision.Enabled = True
        lblSuccess.Text = "Successfully Entered"
        lblSuccess.Visible = True
        txtSearchName.Text = ""
        dlClientNames.SelectedValue = "0"


        

        'Put the page back into insert mode

        PostBack.Value = False


    End Sub

    Protected Sub PopulateClientDrop()

        Dim Sql As String
        Dim UID As Integer
        Dim Records As DbDataReader
        'Dim Params As New Hashtable
        Dim First As New ListItem
        Dim Params(0) As GenParameter

        If txtSearchName.Text = "" Then
            PopulateClientFirst()
            Return
        End If


        UID = Request.Cookies("Profile").Item("ExecutiveID")

        Sql = "Select CompanyAssignments.ClientID AS 'ClientID', ClientMaster.ClientName AS 'ClientName' from CompanyAssignments INNER JOIN ClientMaster" & _
        " ON ClientMaster.ClientID = CompanyAssignments.ClientID" & _
        " WHERE ClientMaster.ClientName LIKE CONCAT('%',?ClientName,'%') AND CompanyAssignments.ExecutiveID = " & UID & _
        " ORDER BY ClientMaster.ClientName"

        'Params.Add("?ClientName", txtSearchName.Text.ToString)
        Params(0) = New GenParameter("?ClientName", txtSearchName.Text, Data.DbType.String)

        Records = GenHelper.ExecuteReader(Sql, Params, ConfigurationManager.ConnectionStrings.Item("MySqlConnString").ToString())

        dlClientNames.Items.Clear()
        First.Text = "Select a Client"
        First.Value = "0"
        First.Selected = True
        dlClientNames.DataSource = Records
        dlClientNames.DataBind()
        dlClientNames.Items.Add(First)
        Records.Close()

    End Sub

    Protected Sub txtSearchName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearchName.TextChanged
        PopulateClientDrop()
        lblSuccess.Visible = False
    End Sub

    Protected Sub PopulateClientFirst()

        Dim FirstClient As New ListItem

        dlClientNames.Items.Clear()
        FirstClient.Text = "Select a Client"
        FirstClient.Value = "0"
        FirstClient.Selected = True
        dlClientNames.Items.Add(FirstClient)

    End Sub

    
End Class
